package jp.chiheisen.httpserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.activation.FileTypeMap;

import jp.chiheisen.common.CloseUtils;
import jp.chiheisen.common.ResourceInputStream;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

public class Response {
	/** HTTPステータスコード 200:OK */
	private static final int HTTP_OK = 200;
	/** HTTPステータスコード 404:NOT FOUND */
	private static final int HTTP_NOT_FOUND = 404;
	
	/** HTTPレスポンス 404:NOT FOUND */
	private static final String HTTP_RESPONSE_NOT_FOUND = "META-INF/not_found.html";
	
	/** 要求・応答クラス */
	private final HttpExchange exchange;
	
	public Response(HttpExchange exchange){
		if (exchange == null) {
			throw new NullPointerException("exchange");
		}
		this.exchange = exchange;
	}
	
	public void send(File file) 
			throws IOException, FileNotFoundException {
		Headers headers = exchange.getResponseHeaders();
		headers.set("Content-Type", FileTypeMap.getDefaultFileTypeMap().getContentType(file));
		exchange.sendResponseHeaders(HTTP_OK, file.length());

		byte[] buf = new byte[8192];
		int len;
		BufferedInputStream input = null;
		try {
			input = new BufferedInputStream(new FileInputStream(file));
			BufferedOutputStream responseBody = new BufferedOutputStream(
					exchange.getResponseBody());
			while ((len = input.read(buf)) != -1) {
				responseBody.write(buf, 0, len);
			}
			responseBody.close();
		} finally {
			CloseUtils.safeClose(input);
		}
	}
	
	public void sendNotFound() throws IOException{
		Headers headers = exchange.getResponseHeaders();
		headers.set("Content-Type", "text/html");
		exchange.sendResponseHeaders(HTTP_NOT_FOUND, 0);
		
		BufferedReader reader = null;
		try{
			reader = new BufferedReader(new InputStreamReader(new ResourceInputStream(HTTP_RESPONSE_NOT_FOUND)));
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(exchange.getResponseBody()));
			String buf;
			while((buf = reader.readLine()) != null){
				String replaced = buf.replaceAll("<url />", exchange.getRequestURI().getPath());
				writer.write(replaced);
			}
			writer.close();
		}finally{
			CloseUtils.safeClose(reader);
		}
	}
}
